package com.zpeb.pdd.filter;

import com.alibaba.fastjson.JSONObject;
import com.sun.corba.se.impl.oa.toa.TOA;
import com.zpeb.pdd.entity.User;
import com.zpeb.pdd.service.UserInfo;
import com.zpeb.pdd.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName pdd
 * @Description: TODO
 * @date ${DAT}14:30
 */
@Component
public class ParamInterceptor implements HandlerInterceptor {

    @Autowired
    UserInfo userInfo;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null || token.equals("")){
            returnErrorContent(401,response,"用户信息失效或者未登录请返回登录页面");
            return false;
        }
        //从redis中获取对应的用户名
        String userName = redisTemplate.opsForValue().get(token);
        //从数据库核实userName是否存在对应的信息
        User user = userInfo.getPasswordByUsername(userName);
        if (user == null){
            returnErrorContent(401,response,"用户信息失效或者未登录请返回登录页面");
            return false;
        }else {
            return true;
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

        private void returnErrorContent(int code, HttpServletResponse response, String msg) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(code);

        ServletOutputStream out=null;
        try {
            JSONObject res = new JSONObject();
            res.put("status", code);
            res.put("msg", msg);
            out = response.getOutputStream();
            out.write(res.toString().getBytes("utf-8"));
            out.flush();
            out.close();
        } catch (IOException e) {

        }

    }
}
